package com.laundry.repository;

import com.laundry.entity.Merchant;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;

@Repository
public interface MerchantRepository extends JpaRepository<Merchant, Long> {
    
    Page<Merchant> findByStatus(Merchant.MerchantStatus status, Pageable pageable);
    
    @Query("SELECT m FROM Merchant m WHERE m.status = :status AND m.name LIKE %:keyword%")
    Page<Merchant> findByStatusAndNameContaining(@Param("status") Merchant.MerchantStatus status, 
                                               @Param("keyword") String keyword, 
                                               Pageable pageable);
    
    @Query("SELECT m FROM Merchant m WHERE m.status = 'ACTIVE' ORDER BY m.rating DESC")
    List<Merchant> findTopRatedMerchants(Pageable pageable);
    
    @Query("SELECT m FROM Merchant m WHERE m.status = 'ACTIVE' ORDER BY m.orderCount DESC")
    List<Merchant> findPopularMerchants(Pageable pageable);
    
    @Query(value = "SELECT m.* FROM merchants m WHERE m.status = 'ACTIVE' AND " +
           "ST_Distance_Sphere(POINT(m.longitude, m.latitude), POINT(:longitude, :latitude)) <= :radius " +
           "ORDER BY ST_Distance_Sphere(POINT(m.longitude, m.latitude), POINT(:longitude, :latitude))",
           nativeQuery = true)
    List<Merchant> findNearbyMerchants(@Param("latitude") BigDecimal latitude, 
                                     @Param("longitude") BigDecimal longitude, 
                                     @Param("radius") Double radius);
}
